#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>

using namespace std;

int g_value = 100;
//__thread int g_value = 100;

void *callfunc1(void *args)
{
    // const char* name = static_cast<const char*>(args);
    int cnt = 5;
    while (cnt--)
    {
        // pthread_t pthread_self(void);
        // printf("%s:%p\n", name, pthread_self());
        sleep(1);
    }

    return (void *)2;
}

void *callfunc2(void *args)
{
    // const char* name = static_cast<const char*>(args);
    int cnt = 5;
    while (cnt--)
    {
        // pthread_t pthread_self(void);
        // printf("%s:%p\n", name, pthread_self());
        sleep(1);
    }

    return (void *)3;
}

void *callfunc(void *args)
{
    // const char* name = static_cast<const char*>(args);
    // int cnt = 3;
    while (true)
    {
        // pthread_t pthread_self(void);
        // printf("%s:%p\n", name, pthread_self());
        // cout << "thread " << pthread_self() << "g_value : " << g_value
        //<< " &g_value : " << &g_value << endl;

        cout << "thread " << pthread_self() << " LWP："<<  ::syscall(SYS_gettid) << endl;
        //++g_value;
        sleep(1);
    }
}

int main()
{
    pthread_t tid1;
    pthread_t tid2;
    pthread_t tid3;
    PTHREAD_CANCELED;

    // int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);
    pthread_create(&tid1, nullptr, callfunc, (void *)"thread 1");
    pthread_create(&tid2, nullptr, callfunc, (void *)"thread 2");
    pthread_create(&tid3, nullptr, callfunc, (void *)"thread 3");

    // int pthread_cancel(pthread_t thread);
    // void *ret3 = nullptr;
    // pthread_cancel(tid3);
    // pthread_join(tid3, &ret3);
    // printf("线程3结束啦...,ret3 = %d\n", ret3);

    // while(true)
    //{
    cout << "主线程..." << endl;
    // sleep(7);
    // sleep(1);
    //}

    // void *ret1 = nullptr;
    // void *ret2 = nullptr;

    // int pthread_join(pthread_t thread, void **value_ptr);
    pthread_join(tid1, nullptr); // 第二参数是输出型参数,主线程会在这里阻塞等待线程结束
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);

    // printf("ret1: %p\n", ret1);
    // printf("ret2: %p\n", ret2);

    return 0;
}